// PipeReadThread.cpp: implementation of the CPipeReadThread class.
//
//////////////////////////////////////////////////////////////////////
// Pipe read thread
// Luey (LiuYu@LiuYu.com)
// 2008-08-31
//////////////////////////////////////////////////////////////////////////

#include "StdAfx.h"
#include "PipeReadThread.h"

CPipeReadThread::CPipeReadThread(void)
{
}

CPipeReadThread::~CPipeReadThread(void)
{
}

DWORD CPipeReadThread::ThreadFunc(LP_PARAMETER pParameter)
{
	ATLTRACE("Start routine %s [%s (line: %d, compile: %s )] \n", __FUNCTION__, __FILE__, __LINE__, __TIMESTAMP__);

	try
	{
		// Parameter check
		if (pParameter == NULL)
		{
			return UNDEFINED_ERROR;
		}

		// Notify listener that thread is start
		CPipeReadThreadListener * pListener = pParameter->pListener;
		if (pListener != NULL)
		{
			pListener->PipeReadThreadStart();
			pListener->PipeReadThreadLog(TEXT("Pipe read thread start"));
		}

		BOOL bSuccess;
		DWORD dwRead;
		CHAR Buffer[MAX_BUFFER_LENGTH];

		// Read from pipe.
		for (;;) 
		{
			bSuccess = ReadFile(pParameter->hPipe, Buffer, MAX_BUFFER_LENGTH, &dwRead, NULL);
			if (! bSuccess || dwRead == 0)
			{
				ATLTRACE("Read from pipe fail, break from reading [%s in %s (line: %d )] \n", __FUNCTION__, __FILE__, __LINE__);
				break;
			}

			// Send data to listener
			if (pListener != NULL)
			{
				pListener->PipeReadThreadReceive(Buffer, dwRead);
			}
		}

		// Tell listener that thread stop
		if (pListener != NULL)
		{
			pListener->PipeReadThreadStop();
		}

		return SUCCESS;
	}
	catch(...)
	{
		ATLTRACE("Exception [%s in %s (line: %d, compile: %s )] \n", __FUNCTION__, __FILE__, __LINE__, __TIMESTAMP__);
		return UNDEFINED_ERROR;
	}
}

HANDLE CPipeReadThread::StartThread(LP_PARAMETER pParameter, LPDWORD lpThreadId)
{
	ATLTRACE("Start routine %s [%s (line: %d, compile: %s )] \n", __FUNCTION__, __FILE__, __LINE__, __TIMESTAMP__);

	if (pParameter == NULL)
	{
		ATLTRACE("Invalid parameter [%s in %s (line: %d, compile: %s )] \n", __FUNCTION__, __FILE__, __LINE__, __TIMESTAMP__);
		return NULL;
	}

	try
	{
		pParameter->hThisThread = CreateThread(	NULL, 0,
												reinterpret_cast<LPTHREAD_START_ROUTINE>(CPipeReadThread::ThreadFunc),
												pParameter,
												0,
												&(pParameter->dwThisThreadId));
		if (lpThreadId != NULL)
		{
			*lpThreadId = pParameter->dwThisThreadId;
		}

		return pParameter->hThisThread;
	}
	catch(...)
	{
		ATLTRACE("Exception [%s in %s (line: %d, compile: %s )] \n", __FUNCTION__, __FILE__, __LINE__, __TIMESTAMP__);
		return NULL;
	}
}